import { defineStore } from 'pinia';
import { ref, computed, nextTick } from 'vue';
import type { ComponentSize } from 'element-plus';
import tinycolor from 'tinycolor2';

// Define the type for XML parser selection
export type XmlParserType = 'dom' | 'fast-xml' | 'libxml2';

// REMOVED FormattingOptions interface and related state/actions

export const useUniversalSettingsStore = defineStore('universal-settings', () => {

    // --- State ---
    const darkMode = ref(false);
    const themeColor = ref('#409EFF'); // Default Element Plus primary color
    const componentSize = ref<ComponentSize>('default');
    const rememberLastFolder = ref(true);
    // --- NEW: State for XML parser selection ---
    const selectedXmlParser = ref<XmlParserType>('dom'); // Default to DOMParser
    // Add other truly universal settings here if needed in the future
    // Examples: language preference, global UI density etc.

    // --- Getters ---
    const currentTheme = computed(() => darkMode.value ? 'dark' : 'light');

    // --- Actions ---
    const setDarkMode = (value: boolean) => {
        darkMode.value = value;
        applyTheme();
    };

    const toggleDarkMode = () => {
        darkMode.value = !darkMode.value;
        applyTheme();
    };

    // Keep the animation logic as it's UI-related and general
    const toggleDarkModeWithAnimation = async (x: number, y: number) => {
        const isAppearanceTransition =
            typeof (document as any).startViewTransition === 'function' &&
            !window.matchMedia('(prefers-reduced-motion: reduce)').matches;

        if (!isAppearanceTransition) {
            console.warn('View Transitions API not supported or reduced motion enabled, falling back to simple toggle.');
            toggleDarkMode();
            return;
        }

        const endRadius = Math.hypot(
            Math.max(x, window.innerWidth - x),
            Math.max(y, window.innerHeight - y)
        );

        document.documentElement.style.setProperty('--clip-x', `${x}px`);
        document.documentElement.style.setProperty('--clip-y', `${y}px`);
        document.documentElement.style.setProperty('--clip-r-end', `${endRadius}px`);

        const transition = (document as any).startViewTransition(async () => {
            darkMode.value = !darkMode.value;
            applyTheme();
            await nextTick();
        });

        transition.ready.then(() => {
            const smallCircle = `circle(0px at var(--clip-x) var(--clip-y))`;
            const largeCircle = `circle(var(--clip-r-end) at var(--clip-x) var(--clip-y))`;

            document.documentElement.animate(
                {
                    clipPath: [smallCircle, largeCircle],
                },
                {
                    duration: 500,
                    easing: 'ease-in-out',
                    pseudoElement: '::view-transition-new(root)',
                }
            );
        });
    };

    const setThemeColor = (color: string) => {
        themeColor.value = color;
        applyTheme();
    };

    const setComponentSize = (size: ComponentSize) => {
        componentSize.value = size;
    };
    
    const setRememberLastFolder = (remember: boolean) => {
        rememberLastFolder.value = remember;
    }

    // --- NEW: Action to set XML parser ---
    const setSelectedXmlParser = (parser: XmlParserType) => {
        const validParsers: XmlParserType[] = ['dom', 'fast-xml', 'libxml2'];
        if (validParsers.includes(parser)) {
            selectedXmlParser.value = parser;
        } else {
            console.warn(`Invalid XML parser selected: ${parser}`);
        }
    };

    // Central theme application logic
    const applyTheme = () => {
        document.documentElement.classList.toggle('dark', darkMode.value);
        
        const color = tinycolor(themeColor.value);
        if (!color.isValid()) {
            console.error("Invalid theme color selected:", themeColor.value);
            return;
        }

        document.documentElement.style.setProperty('--el-color-primary', color.toHexString());

        const lightMix = 80;
        const darkMix = 20;

        const light8 = tinycolor.mix('#ffffff', color, 100 - lightMix).toHexString();
        const dark2 = tinycolor.mix('#000000', color, 100 - darkMix).toHexString();
        const light9Color = tinycolor.mix('#ffffff', color, 90);
        const light9Hex = light9Color.toHexString();
        const light9Rgb = light9Color.toRgb();

        document.documentElement.style.setProperty('--el-color-primary-light-8', light8);
        document.documentElement.style.setProperty('--el-color-primary-dark-2', dark2);
        document.documentElement.style.setProperty('--el-color-primary-light-9', light9Hex);
        document.documentElement.style.setProperty('--el-color-primary-light-9-rgb', `${light9Rgb.r}, ${light9Rgb.g}, ${light9Rgb.b}`);

        console.log('Applied universal theme:', {
            primary: color.toHexString(),
            darkMode: darkMode.value
        });
    };

    return {
        // State
        darkMode,
        themeColor,
        componentSize,
        rememberLastFolder,
        selectedXmlParser,

        // Getters
        currentTheme,

        // Actions
        setDarkMode,
        toggleDarkMode,
        toggleDarkModeWithAnimation,
        setThemeColor,
        setComponentSize,
        setRememberLastFolder,
        setSelectedXmlParser,
        applyTheme, // Expose applyTheme if it needs to be called externally (e.g., on mount)
    };
}, {
    persist: {
        key: 'jdfsight-universal-settings', // New key for universal settings
        // No paths needed if we persist everything in this store
        // paths: ['darkMode', 'themeColor', 'componentSize', 'rememberLastFolder', 'selectedXmlParser'] 
        debug: import.meta.env.DEV,
    }
}); 